// components/CountdownModal.tsx
import React, {useState, useEffect, ReactNode} from 'react';
import {useRouter} from 'next/router';
import {getDomain} from "@/utils";
import styles from './CountdownModal.module.css';

interface CountdownModalProps {
    isOpen: boolean;
    onClose: () => void;
    redirectTo: string;
    children?: ReactNode;  // 添加children属性，类型为ReactNode
}

const CountdownModal: React.FC<CountdownModalProps> = ({isOpen, onClose, redirectTo, children}) => {
    const [seconds, setSeconds] = useState<number>(5);
    const router = useRouter();

    useEffect(() => {
        let interval: NodeJS.Timeout | null = null;

        if (isOpen && seconds > 0) {
            interval = setInterval(() => {
                setSeconds(seconds => seconds - 1);
            }, 1000);
        } else if (seconds === 0) {
            window.location.href = getDomain() + redirectTo;
            // router.push(redirectTo).then(() => {});
            onClose(); // 关闭 Modal 并重置计时
        }

        return () => {
            if (interval) {
                clearInterval(interval);
            }
        };
    }, [isOpen, seconds, router, redirectTo, onClose]);

    if (!isOpen) {
        return null;
    }

    return (
        <div className={styles.countdownmodal} >
            {children}
            <span className={styles.countdown}>
            页面将在 {seconds} 秒后跳转
            </span>
            {/*<button onClick={onClose}>关闭</button>*/}
        </div>
    );
};

export default CountdownModal;
